package com.licq.ldoc.parser.impl;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.commons.beanutils.ConstructorUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.licq.ldoc.domain.Attribute;
import com.licq.ldoc.domain.Element;
import com.licq.ldoc.parser.AnnotationParsee;
import com.licq.ldoc.utils.PropertiesUtils;

/**
 * 
 * @author liujian
 *
 */
public abstract class AnnotationParsees {
	private static transient Log logger = LogFactory.getLog(AnnotationParsees.class);
	
	private static final String CONFIG_LOCATION = "SupportAnnotations.properties";
	
	private static AnnotationParsee annotationParsee = AnnotationParsee.NULL_PARSER;
	
	static {
		initiateAnnotationParsee();
	}
	
	public static void parse(Element element, Annotation[] annotations) {
		for (Annotation annotation : annotations) {
			annotationParsee.parse(element, annotation);
		}
	}
	
	public static void parse(Attribute attribute, Annotation[] annotations) {
		for (Annotation annotation : annotations) {
			annotationParsee.parse(attribute, annotation);
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void initiateAnnotationParsee() {
		try {
			Properties supportedAnnotations = PropertiesUtils.loadAllProperties(CONFIG_LOCATION);
			for (Entry<Object, Object> supportedAnnotation : supportedAnnotations.entrySet()) {
				String annotationClazzName = (String) supportedAnnotation.getKey();
				String parseeClazzName = (String) supportedAnnotation.getValue();
				Class<? extends Annotation> annotationClazz;
				try {
					annotationClazz = (Class<? extends Annotation>) Class.forName(annotationClazzName);
				} catch (ClassNotFoundException e) {
					if (logger.isErrorEnabled()) {
						logger.error(String.format("class %s not found.", annotationClazzName));
					}
					throw new RuntimeException(e);
				}
				Class<? extends AnnotationParsee> parseeClazz;
				try {
					parseeClazz = (Class<? extends AnnotationParsee>) Class.forName(parseeClazzName);
				} catch (ClassNotFoundException e) {
					if (logger.isErrorEnabled()) {
						logger.error(String.format("class %s not found.", parseeClazzName));
					}
					throw new RuntimeException(e);
				}
				
				annotationParsee = (AnnotationParsee) ConstructorUtils.invokeConstructor(parseeClazz, 
						annotationParsee);
				annotationParsee.setParseClazz(annotationClazz);
			}
		} catch (IOException e) {
			if (logger.isErrorEnabled()) {
				logger.error(String.format("load supported annotation parsees config file %s failed.", 
						CONFIG_LOCATION
					)
				);
			}
			throw new RuntimeException(e);
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("initiate annotation parsee failed, plz have a check.");
			}
			throw new RuntimeException(e);
		}
	}

}
